// 用户相关的状态

import { createSlice } from '@reduxjs/toolkit';
import { request } from '@/utils';
import { getToken,setToken } from '@/utils/token';

const userStore = createSlice({
  name: 'user',
  // 数据状态
  initialState: {
    token: getToken() || '',
  },
  // 同步修改方法
  reducers: {
    setUserToken(state, action) {
      state.token = action.payload;
      // localStorage存一份
      setToken( state.token);
    },
    setUserInfo (state, action) {
      state.userInfo = action.payload
    }
  },
});

// 解构出actionCreater
const { setUserToken,setUserInfo  } = userStore.actions;

// 获取reducer函数
const userReducer = userStore.reducer;

// 异步方法封装
const fetchLogin = loginForm => {
  return async dispatch => {
    // 1.发送异步请求
    const res = await request.post('/authorizations', loginForm);
    // 2.提交同步action进行token的存入
    dispatch(setUserToken(res.data.token));
  };
};

const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await request.get('/user/profile')
    dispatch(setUserInfo(res.data))
  }
}

export { fetchLogin, setUserToken,fetchUserInfo  };

export default userReducer;
